package com.ruyiadmin.springcloud.producer.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruyiadmin.springcloud.producer.common.annotations.system.Log;
import com.ruyiadmin.springcloud.producer.common.annotations.system.Permission;
import com.ruyiadmin.springcloud.producer.common.core.business.enums.OperationType;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.ActionResult;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.QueryCondition;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.QueryItem;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.QueryResult;
import com.ruyiadmin.springcloud.producer.common.core.system.enums.DataType;
import com.ruyiadmin.springcloud.producer.common.core.system.enums.QueryMethod;
import com.ruyiadmin.springcloud.producer.common.exceptions.RuYiAdminCustomException;
import com.ruyiadmin.springcloud.producer.domain.entity.system.SysImportConfig;
import com.ruyiadmin.springcloud.producer.domain.entity.system.SysImportConfigDetail;
import com.ruyiadmin.springcloud.producer.service.iservices.system.ISysImportConfigDetailService;
import com.ruyiadmin.springcloud.producer.service.iservices.system.ISysImportConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * <p>
 * 导入配置主表 前端控制器
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-12
 */
@RestController
@RequestMapping("/ImportConfigManagement")
@Api(tags = "系统导入配置管理服务")
@RequiredArgsConstructor
public class SysImportConfigController {

    //region 配置服务私有属性

    private final ISysImportConfigService importConfigService;
    private final ISysImportConfigDetailService detailService;

    //endregion

    //region 查询导入配置列表

    @PostMapping("/Post")
    @ApiOperation(value = "查询导入配置列表")
    @Log(OperationType = OperationType.QueryList)
    @Permission(permission = "import:config:query:list")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public QueryResult<SysImportConfig> queryByPage(@RequestBody QueryCondition queryCondition)
            throws ExecutionException, InterruptedException {
        CompletableFuture<QueryResult<SysImportConfig>> future = CompletableFuture.supplyAsync(() -> {
            QueryWrapper<SysImportConfig> wrapper = new QueryWrapper<>();//设置条件
            queryCondition.getQueryWrapper(wrapper);//转化查询条件、转化排序条件
            Page<SysImportConfig> page = new Page<>(queryCondition.getPageIndex(),
                    queryCondition.getPageSize());//初始化page

            this.importConfigService.page(page, wrapper);//执行查询
            long total = page.getTotal();//总数
            List<SysImportConfig> rs = page.getRecords();//结果

            return QueryResult.success(total, rs);
        });
        return future.get();
    }

    //endregion

    //region 按编号获取导入配置

    @GetMapping("/GetById/{id}")
    @ApiOperation(value = "按编号获取导入配置")
    @Log(OperationType = OperationType.QueryEntity)
    @Permission(permission = "import:config:query:list")
    public ActionResult getById(@PathVariable("id") String id) throws ExecutionException, InterruptedException {
        CompletableFuture<ActionResult> future = CompletableFuture.supplyAsync(() ->
                ActionResult.success(this.importConfigService.getById(id)));
        return future.get();
    }

    //endregion

    //region 新增导入配置信息

    @PostMapping("/AddConfig")
    @ApiOperation(value = "新增导入配置信息")
    @Log(OperationType = OperationType.AddEntity)
    @Permission(permission = "import:config:add:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult add(@Valid @RequestBody SysImportConfig importConfig) {
        return ActionResult.success(this.importConfigService.save(importConfig));
    }

    //endregion

    //region 修改导入配置信息

    @PutMapping("/EditConfig")
    @ApiOperation(value = "修改导入配置信息")
    @Log(OperationType = OperationType.EditEntity)
    @Permission(permission = "import:config:edit:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult edit(@Valid @RequestBody SysImportConfig importConfig) {
        return ActionResult.success(this.importConfigService.updateById(importConfig));
    }

    //endregion

    //region 批量删除导入配置信息

    @DeleteMapping("/DeleteConfigs/{ids}")
    @ApiOperation(value = "批量删除导入配置信息")
    @Log(OperationType = OperationType.DeleteEntity)
    @Permission(permission = "import:config:del:entities")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult deleteRange(@PathVariable("ids") String ids) {
        //导入配置信息删除检测
        this.deleteCheck(ids);
        //删除数据
        List<String> array = Arrays.asList(ids.split(","));
        return ActionResult.success(this.importConfigService.removeByIds(array));
    }

    //endregion

    //region 导入配置信息删除检测

    /**
     * 导入配置信息删除检测
     *
     * @param ids 编号数组
     */
    private void deleteCheck(String ids) {
        String[] array = ids.split(",");
        //删除校验
        for (String item : array) {
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setQueryItems(new ArrayList<>());
            queryCondition.getQueryItems().add(new QueryItem("PARENT_ID", DataType.Guid, QueryMethod.Equal, item));
            QueryWrapper<SysImportConfigDetail> wrapper = new QueryWrapper<>();
            queryCondition.getQueryWrapper(wrapper);
            int count = this.detailService.list(wrapper).size();
            if (count > 0) {
                throw new RuYiAdminCustomException("config contains subitems,can not be deleted");
            }
        }
    }

    //endregion

    //region 按父键获取配置明细

    @GetMapping("/GetByParentId/{parentId}")
    @ApiOperation(value = "按父键获取配置明细")
    @Log(OperationType = OperationType.QueryList)
    @Permission(permission = "import:config:query:list")
    public ActionResult getByParentId(@PathVariable("parentId") String parentId)
            throws ExecutionException, InterruptedException {
        CompletableFuture<ActionResult> future = CompletableFuture.supplyAsync(() -> {
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setQueryItems(new ArrayList<>());
            queryCondition.getQueryItems().add(
                    new QueryItem("PARENT_ID", DataType.Guid, QueryMethod.Equal, parentId));

            QueryWrapper<SysImportConfigDetail> wrapper = new QueryWrapper<>();
            queryCondition.getQueryWrapper(wrapper);

            List<SysImportConfigDetail> list = this.detailService.list(wrapper)
                    .stream()
                    .sorted(Comparator.comparing(SysImportConfigDetail::getCreateTime))
                    .collect(Collectors.toList());

            return ActionResult.success(list);
        });
        return future.get();
    }

    //endregion

    //region 添加导入配置明细

    @PostMapping("/AddConfigDetail")
    @ApiOperation(value = "添加导入配置明细")
    @Log(OperationType = OperationType.AddEntity)
    @Permission(permission = "import:config:add:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult add(@Valid @RequestBody SysImportConfigDetail configDetail) {
        return ActionResult.success(this.detailService.save(configDetail));
    }

    //endregion

    //region 编辑导入配置明细

    @PutMapping("/EditConfigDetail")
    @ApiOperation(value = "编辑导入配置明细")
    @Log(OperationType = OperationType.EditEntity)
    @Permission(permission = "import:config:edit:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult edit(@Valid @RequestBody SysImportConfigDetail configDetail) {
        return ActionResult.success(this.detailService.updateById(configDetail));
    }

    //endregion

    //region 批量删除配置明细

    @DeleteMapping("/DeleteConfigDetails/{ids}")
    @ApiOperation(value = "批量删除配置明细")
    @Log(OperationType = OperationType.DeleteEntity)
    @Permission(permission = "import:config:del:entities")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult deleteDetailRange(@PathVariable("ids") String ids) {
        //删除数据
        List<String> array = Arrays.asList(ids.split(","));
        return ActionResult.success(this.detailService.removeByIds(array));
    }

    //endregion

}
